﻿using Sys.Common;
using Sys.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Sys.Core.Tour
{
    /// <summary>
    /// 图片业务
    /// </summary>
    public class ImageBll : ExampleBase<TourImage, ImageBll>
    {
        /// <summary>
        /// 排序实体
        /// </summary>
        public IQueryable<TourImage> SortEntities
        {
            get { return Entities.OrderBy(m => m.IntSort); }
        }

        /// <summary>
        /// 写入图片
        /// </summary>
        /// <param name="tag">标记</param>
        /// <param name="id">表单编号</param>
        /// <param name="list">图片列表</param>
        public void SetImages(string tag, string id, List<TourImage> list)
        {
            DateTime now = DateTime.Now;

            for (int i = 0; i < list.Count; i++)
            {
                list[i].ID = StringHelper.GetGuid();
                list[i].IntSort = i + 1;
                list[i].Tag = tag;
                list[i].TableID = id;
                list[i].InsertTime = now;
                list[i].Img = list[i].Img.Substring(list[i].Img.LastIndexOf('/') + 1);
            }

            Delete(m => m.Tag.Equals(tag) && m.TableID.Equals(id)); Insert(list);
        }

        /// <summary>
        /// 获取图片
        /// </summary>
        /// <param name="tag">标记</param>
        /// <param name="id">表单编号</param>
        /// <returns>图片列表</returns>
        public IQueryable<TourImage> GetImages(string tag, string id)
        {
            return SortEntities.Where(m => m.Tag.Equals(tag) && m.TableID.Equals(id));
        }

        /// <summary>
        /// 获取封面图片
        /// </summary>
        /// <param name="tag">标记</param>
        /// <param name="id">表单编号</param>
        /// <returns>封面图片</returns>
        public string GetFront(string tag, string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                var front = GetImages(tag, id).Where(m => m.IsCover).FirstOrDefault();

                if (front == null)
                {
                    front = GetImages(tag, id).FirstOrDefault();
                }

                if (front != null) { return front.Img; }
            }

            return "null.png";
        }
        
        /// <summary>
        /// 根据标记和编号删除图片
        /// </summary>
        /// <param name="tag">标记</param>
        /// <param name="id">编号</param>
        /// <returns>受影响行数</returns>
        public int Delete(string tag, string id)
        {
            return Delete(m => m.Tag.Equals(tag) && m.TableID.Equals(id));
        }
    }
}
